package com.fashion.utils;

import com.fashion.model.InLineWord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidParameterException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: juventus
 * Date: 11-6-8
 * Time: 下午5:53
 */
public class StringUtils {
    private static String DATE_TIME_FORMAT = "yyMMddHHmmssSSS";
    private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
    public static final String Persistent_Html_Folder = "persistent";
    public static final String TagCloudHtmlName = "tagcloud.html";
    public static final String TagCloudHtmlUrl = "/tagcloud.html";
    private static final String regExpress = "(?i)/n-\\d{15}(-?\\d{0,3})\\.html";
    public static final String DefaultBaseUrl = "http://www.fengsung.com";

    public static boolean isNullOrEmpty(String input) {
        if (null == input) {
            return true;
        }

        return input.trim().isEmpty();
    }

    public static String createGuid() {
        return UUID.randomUUID().toString();
    }

    public static String createTimeStamp() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT);

        return dateFormat.format(new Date());
    }

    public static int parseStringToInt(String source) {
        if (isNullOrEmpty(source)) {
            return 0;
        }

        int number = 0;

        try {
            number = Integer.parseInt(source);
        } catch (NumberFormatException ignored) {
        }

        return number;
    }

    public static String createTimeStamp(String format) {
        if (isNullOrEmpty(format)) {
            format = DATE_TIME_FORMAT;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat(format);

        return dateFormat.format(new Date());
    }

    public static List<String> splitToList(String source, String splitter) {
        return splitWithSpecialChar(source, splitter);
    }

    public static int toBooleanInt(String value) {
        if (null == value) {
            return 0;
        }

        if ("true".equalsIgnoreCase(value.trim())) {
            return 1;
        }

        return 0;
    }

    public static List<String> splitWithSpecialChar(String source, String splitter) {
        List<String> results = new ArrayList<String>();

        if (null == source || null == splitter) {
            return results;
        }

        source = source.trim();

        if ("".equals(source)) {
            results.add(source);
            return results;
        }

        if ("".equals(splitter)) {
            results.add(source);
            return results;
        }

        while (source.length() > 0) {
            int index = source.indexOf(splitter);

            if (index == -1) {
                results.add(source);
                break;
            }

            String sub = source.substring(0, index);
            if (!"".equals(sub)) {
                results.add(sub);
            }

            if (index == source.length() - splitter.length()) {
                break;
            }

            source = source.substring(index + splitter.length());

        }

        return results;
    }

    public static String toSequenceValue(int number) {
        if (number < 10) {
            return "0" + number;
        }

        return "" + number;
    }

    public static String connectStrings(List<String> elements, String splitter) {
        if (null == elements) {
            throw new InvalidParameterException("elements can not be null!");
        }

        if (null == splitter) {
            throw new InvalidParameterException("splitter can not be null!");
        }

        if (elements.size() == 0) {
            return "";
        }

        StringBuffer result = new StringBuffer("");

        for (String element : elements) {
            result.append(element);
            result.append(splitter);
        }

        result.delete(result.length() - splitter.length(), result.length());

        return result.toString();
    }

    public static boolean isChinese(String input) {
        if (null == input) {
            return false;
        }

        if (0 == input.length()) {
            return false;
        }

        for (int i = 0; i < input.length(); i++) {
            String piece = input.substring(i, i + 1);

            if (piece.matches("[\\u4e00-\\u9fbb]+")) {
                return true;
            }
        }

        return false;
    }

    public static String generateNameByYearAndMonth() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");

        return dateFormat.format(new Date());
    }

    public static String truncateString(String input, int maxLength) {
        if (isNullOrEmpty(input)) {
            return "";
        }

        int currentLength = input.length();
        if (currentLength > maxLength) {
            StringBuilder result = new StringBuilder();
            result.append(input.substring(0, maxLength - 1));
            result.append("...");

            return result.toString();
        }

        return input;
    }

    public static String findSuffixName(String fileName) {
        if (isNullOrEmpty(fileName)) {
            return "";
        }

        if (!fileName.contains(".")) {
            return "";
        }

        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static String replaceWithRegex(String regex, String originalContent, String replacement) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(originalContent);

        return matcher.replaceAll(replacement);
    }

    public static UrlKeyword makeUrlKeyword(String rawUrl) {
        try {
            return new UrlKeyword(rawUrl, URLEncoder.encode(rawUrl, "GB2312"));
        } catch (UnsupportedEncodingException e) {
            logger.error("Error in encoding url: " + rawUrl, e);
            return null;
        }
    }

    public static String removeSlash(String columnUrl) {
        String output = columnUrl;

        if (columnUrl.endsWith("/")) {
            output = columnUrl.substring(0, columnUrl.length() - 1);
        }

        return output;
    }

    public static String captureAfter(String original, String symbol) {
        return original.substring(original.lastIndexOf(symbol) + symbol.length(), original.length());
    }

    public static String addInline(String original, InLineWord inLine) throws UnsupportedEncodingException {
        if(isNullOrEmpty(original)) {
            logger.error("original text should not be null or empty!");
            return "";
        }

        StringBuilder inLineClause = new StringBuilder("<a target='_blank' style='color: #666666;' href='");

        String inLineUrl = inLine.getUrl();
        String word = inLine.getWord();
        String tagUrl = URLEncoder.encode(word, "GB2312");

        if (!isNullOrEmpty(inLineUrl)) {
            inLineClause.append(inLineUrl).append("' >");
        } else {
            inLineClause.append("/tag/");
            inLineClause.append(tagUrl).append(".html'>");
        }

        inLineClause.append(word).append("</a>");

        return original.replaceFirst(word, inLineClause.toString());
    }

    public static String findPreFolder(String urlString) {
        if (urlString.length() < 4) {
            return "";
        }

        int prefixIndex = urlString.lastIndexOf("n-");

        //Then the urlString is raw id
        if (prefixIndex < 0) {
            return urlString.substring(0, 4);
        }

        //The urlString is like '/n-1301020202987.html'
        return urlString.substring(prefixIndex + 2, prefixIndex + 6);
    }

    public static String findHtmlName(String urlString) {
        String id = urlString.substring(urlString.lastIndexOf("n-") + 2);
        if (id.contains("-1.h")) {
            id = id.substring(0, id.lastIndexOf("-1")) + ".html";
        }

        return id;
    }

    public static boolean isHtmlExpression(String input) {
        Pattern pattern = Pattern.compile(regExpress);
        Matcher matcher = pattern.matcher(input);

        return matcher.matches();
    }

    public static List<String> findAdjacentMonths(Date date, int month) {
        List<String> months = new ArrayList<String>();
        if (month < 0 || month > 3) {
            month = 3;
        }


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMM");
        Calendar calender = Calendar.getInstance();
        calender.setTime(date);
        months.add(simpleDateFormat.format(date));

        for (int i = 1; i < month; i++) {
            calender.add(Calendar.MONTH, -1);
            months.add(simpleDateFormat.format(calender.getTime()));
        }

        return months;
    }

    public static String findBaseUrl(String sourceLink) {
        try {
            URL url = new URL(sourceLink);
            return "http://" + url.getHost();
        } catch (MalformedURLException e) {
            return DefaultBaseUrl;
        }
    }
}
